const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const { User,Student,Teacher,VideoResource,Course,Order,Schedule } = require('../model/model');

// JWT验证中间件
const verifyToken = (req, res, next) => {
  const token = req.headers.authorization;
  if (!token) {
    return res.status(401).json({
      success: false,
      message: '未提供访问令牌'
    });
  }

  try {
    // 移除Bearer前缀
    const actualToken = token.startsWith('Bearer ') ? token.slice(7) : token;
    
    // 这里可以添加JWT验证逻辑
    // 暂时简单检查token是否存在
    if (!actualToken) {
      return res.status(401).json({
        success: false,
        message: '无效的访问令牌'
      });
    }
    
    next();
  } catch (error) {
    return res.status(401).json({
      success: false,
      message: '令牌验证失败'
    });
  }
};

// 权限验证中间件
const checkPermission = (requiredActions) => {
  return async (req, res, next) => {
    try {
      // 从请求头获取用户信息（前端应该传递用户ID）
      const userId = req.headers['user-id'];
      if (!userId) {
        return res.status(401).json({
          success: false,
          message: '未提供用户信息'
        });
      }

      // 简单的权限检查逻辑（基于用户ID前缀）
      let hasPermission = false;
      
      if (userId.startsWith('100')) {
        // 超级管理员拥有所有权限
        hasPermission = true;
      } else if (userId.startsWith('200')) {
        // 教师权限检查
        const teacherPermissions = ['view', 'edit', 'add', 'delete', 'manage_students', 'manage_courses'];
        hasPermission = requiredActions.every(action => teacherPermissions.includes(action));
      }

      if (!hasPermission) {
        return res.status(403).json({
          success: false,
          message: '权限不足'
        });
      }

      next();
    } catch (error) {
      console.error('权限验证错误:', error);
      return res.status(500).json({
        success: false,
        message: '权限验证失败'
      });
    }
  };
};

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, '../public/uploads/avatars');
    // 确保上传目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    console.log('上传目录:', uploadDir);
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 文件名格式: teacher-时间戳-随机数.扩展名
    const ext = path.extname(file.originalname);
    const filename = `teacher-${Date.now()}-${Math.floor(Math.random() * 10000)}${ext}`;
    console.log('生成的文件名:', filename);
    cb(null, filename);
  }
});

// 文件过滤
const fileFilter = (req, file, cb) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('只支持上传JPEG、PNG或GIF格式的图片'), false);
  }
};

// 创建上传中间件
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 500 * 1024 // 限制500KB
  }
});

// 课程视频上传配置
const courseVideoStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    let uploadDir;
    if (file.fieldname === 'video') {
      uploadDir = path.join(__dirname, '../public/uploads/videos');
    } else if (file.fieldname === 'images') {
      uploadDir = path.join(__dirname, '../public/uploads/course-images');
    } else {
      uploadDir = path.join(__dirname, '../public/uploads/course-files');
    }
    
    // 确保上传目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    console.log('课程文件上传目录:', uploadDir);
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname);
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 10000);
    
    let filename;
    if (file.fieldname === 'video') {
      filename = `course-video-${timestamp}-${random}${ext}`;
    } else if (file.fieldname === 'images') {
      filename = `course-image-${timestamp}-${random}${ext}`;
    } else {
      filename = `course-file-${timestamp}-${random}${ext}`;
    }
    
    console.log('生成的课程文件名:', filename);
    cb(null, filename);
  }
});

// 课程文件过滤
const courseFileFilter = (req, file, cb) => {
  if (file.fieldname === 'video') {
    // 视频文件类型
    const allowedVideoTypes = ['video/mp4', 'video/mov', 'video/avi', 'video/wmv', 'video/flv', 'video/mkv'];
    if (allowedVideoTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('只支持上传MP4、MOV、AVI、WMV、FLV或MKV格式的视频'), false);
    }
  } else if (file.fieldname === 'images') {
    // 图片文件类型
    const allowedImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (allowedImageTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('只支持上传JPEG、PNG、GIF或WebP格式的图片'), false);
    }
  } else if (file.fieldname === 'file') {
    // 文档文件类型
    const allowedDocTypes = [
      'application/vnd.ms-powerpoint', // .ppt
      'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .pptx
      'application/msword', // .doc
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
      'application/pdf', // .pdf
      'application/vnd.ms-excel', // .xls
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
      'text/plain' // .txt
    ];
    
    // 也支持通过文件扩展名判断
    const fileName = file.originalname.toLowerCase();
    const supportedExtensions = ['.ppt', '.pptx', '.doc', '.docx', '.pdf', '.xls', '.xlsx', '.txt'];
    const hasValidExtension = supportedExtensions.some(ext => fileName.endsWith(ext));
    
    if (allowedDocTypes.includes(file.mimetype) || hasValidExtension) {
      cb(null, true);
    } else {
      cb(new Error('只支持上传PPT、Word、PDF、Excel、TXT格式的文档'), false);
    }
  } else {
    cb(null, true);
  }
};

// 创建课程上传中间件
const courseUpload = multer({
  storage: courseVideoStorage,
  fileFilter: courseFileFilter,
  limits: {
    fileSize: 500 * 1024 * 1024 // 限制500MB，支持大文件上传
  }
});

// WebSocket setup function
function setupWebSocket(server) {
    console.log('WebSocket setup initialized');
}

// 登录接口;;
router.post('/logins', async (req, res) => {
    try {
        const { username, password } = req.body;
        
        // 验证输入
        if (!username || !password) {
            return res.status(400).json({ message: '用户名和密码不能为空' });
        }
        
        // 查找用户
        const user = await User.findOne({ username }).select('+password');
        if (!user) {
            return res.status(401).json({ message: '用户名或密码错误' });
        }
        
        // 验证密码
        if (password !== user.password) {
            return res.status(401).json({ message: '用户名或密码错误' });
        }
        
        // 获取用户类型
        let role;
        if (user.id.startsWith('100')) {
            role = '超级管理员';
        } else if (user.id.startsWith('200')) {
            role = '教师';
        } else {
            role = '未知角色';
        }
        
        // 生成JWT token
        const jwt = require('jsonwebtoken');
        const token = jwt.sign(
            { 
                id: user.id, 
                username: user.username,
                role: role 
            }, 
            '123', // 使用与expressJWT相同的密钥
            { expiresIn: '24h' }
        );
        
        res.json({
            message: '登录成功',
            token: token, // 返回JWT token
            user: {
                id: user.id,
                username: user.username,
                role: role // 返回中文角色名称
            }
        });
    } catch (error) {
        console.error('登录错误:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

//学生列表
router.get('/students', async (req, res) => {
  try {
      const { 
          name, 
          studentId, 
          class: className, 
          isActive,
          page = 1, 
          pageSize = 5 
      } = req.query;

      // 构建查询条件
      const query = {};
      if (name) query.name = { $regex: name, $options: 'i' };
      if (studentId) query.studentId = studentId;
      if (className) query.class = className;
      if (isActive !== undefined) query.isActive = isActive === 'true';

      // 分页查询
      const [students, total] = await Promise.all([
          Student.find(query)
              .skip((page - 1) * pageSize)
              .limit(parseInt(pageSize))
              .sort({ studentId: 1 }),
          Student.countDocuments(query)
      ]);

      res.json({
          success: true,
          data: students,
          pagination: {
              page: parseInt(page),
              pageSize: parseInt(pageSize),
              total
          }
      });
  } catch (error) {
      console.error('获取学生列表错误:', error);
      res.status(500).json({ 
          success: false,
          message: '获取学生列表失败'
      });
  }
});

// 添加学生
router.post('/students', async (req, res) => {
  try {
    const { name, gender, phone, class: className, averageScore, isActive = true } = req.body;

    // 验证必填字段
    if (!name || !gender || !phone || !className || averageScore === undefined) {
      return res.status(400).json({
        success: false,
        message: '缺少必填字段'
      });
    }

    // 验证手机号格式
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      return res.status(400).json({
        success: false,
        message: '手机号格式不正确'
      });
    }

    // 验证成绩范围
    if (averageScore < 0 || averageScore > 100) {
      return res.status(400).json({
        success: false,
        message: '成绩必须在0-100之间'
      });
    }

    // 生成学生ID（格式：S + 年份后两位 + 4位序号）
    const currentYear = new Date().getFullYear().toString().slice(-2);
    const lastStudent = await Student.findOne({}, {}, { sort: { 'studentId': -1 } });
    let sequence = 1;
    if (lastStudent && lastStudent.studentId) {
      const lastSequence = parseInt(lastStudent.studentId.slice(-4));
      sequence = lastSequence + 1;
    }
    const studentId = `S${currentYear}${sequence.toString().padStart(4, '0')}`;

    // 检查手机号是否已存在
    const existingStudent = await Student.findOne({ phone });
    if (existingStudent) {
      return res.status(400).json({
        success: false,
        message: '该手机号已被注册'
      });
    }

    // 创建新学生
    const newStudent = new Student({
      studentId,
      name,
      gender,
      phone,
      class: className,
      averageScore: parseFloat(averageScore),
      isActive
    });

    await newStudent.save();

    res.status(201).json({
      success: true,
      message: '学生添加成功',
      data: newStudent
    });
  } catch (error) {
    console.error('添加学生错误:', error);
    res.status(500).json({
      success: false,
      message: error.code === 11000 ? '学生已存在' : '添加学生失败'
    });
  }
});

//添加教师
// 添加教师接口（使用multer中间件处理文件上传）
router.post('/addteachers', verifyToken, upload.single('avatar'), async (req, res) => {
  try {
    console.log('收到添加教师请求:', {
      body: req.body,
      file: req.file
    });
    
    // 从请求体中获取当前用户信息，或者使用默认值
    const currentUser = req.body.uploader || 'admin';
    
    // 获取表单数据
    const { 
      name,
      briefIntro = '专注原型设计教学',
      detailedIntro = '',
      phone
    } = req.body;

    // 验证必填字段
    if (!name || !briefIntro) {
      return res.status(400).json({
        success: false,
        message: '姓名和简介是必填字段'
      });
    }

    // 处理头像URL
    let avatarUrl = 'https://randomuser.me/api/portraits/men/1.jpg'; // 默认头像
    if (req.file) {
      avatarUrl = `/uploads/avatars/${req.file.filename}`;
      console.log('使用上传的文件:', avatarUrl);
    } else if (req.body.avatar && typeof req.body.avatar === 'string') {
      // 如果前端传递了头像URL，直接使用
      avatarUrl = req.body.avatar;
      console.log('使用前端传递的URL:', avatarUrl);
    }
    console.log('最终头像URL:', avatarUrl);

    // 创建教师
    const newTeacher = new Teacher({
      name,
      avatar: avatarUrl, // 确保是字符串URL
      briefIntro,
      detailedIntro,
      uploader: currentUser, // 使用当前用户信息
      phone
    });

    console.log('准备保存教师数据:', {
      name: newTeacher.name,
      avatar: newTeacher.avatar,
      briefIntro: newTeacher.briefIntro,
      uploader: newTeacher.uploader
    });

    await newTeacher.save();

    console.log('教师保存成功:', newTeacher._id);

    res.status(201).json({
      success: true,
      data: newTeacher
    });
  } catch (error) {
    console.error('添加教师错误:', error);
    
    let errorMessage = '添加教师失败';
    if (error.code === 11000) {
      errorMessage = '教师已存在';
    } else if (error.name === 'ValidationError') {
      errorMessage = '数据验证失败: ' + Object.values(error.errors).map(e => e.message).join(', ');
    }
    
    res.status(500).json({
      success: false,
      message: errorMessage
    });
  }
});

//教师列表
router.get('/teachers', async (req, res) => {
  try {
      const { 
          name,
          uploader,
          startDate,
          endDate,
          page = 1, 
          pageSize = 10 
      } = req.query;

      // 构建查询条件
      const query = {};
      if (name) query.name = { $regex: name, $options: 'i' };
      if (uploader) query.uploader = uploader;
      
      // 日期范围筛选
      if (startDate || endDate) {
          query.createdAt = {};
          if (startDate) query.createdAt.$gte = new Date(startDate);
          if (endDate) query.createdAt.$lte = new Date(endDate + ' 23:59:59');
      }

      // 分页查询
      const [teachers, total] = await Promise.all([
          Teacher.find(query)
              .skip((page - 1) * pageSize)
              .limit(parseInt(pageSize))
              .sort({ createdAt: -1 }),
          Teacher.countDocuments(query)
      ]);

      res.json({
          success: true,
          data: teachers,
          pagination: {
              current: parseInt(page),
              pageSize: parseInt(pageSize),
              total
          }
      });
  } catch (error) {
      console.error('获取教师列表错误:', error);
      res.status(500).json({ 
          success: false,
          message: '获取教师列表失败'
      });
  }
});

// 修改上传接口（使用multer中间件）
router.post('/upload', verifyToken, upload.single('avatar'), async (req, res) => {
  try {
    console.log('收到上传请求:', req.file);
    
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '请上传有效的图片文件'
      });
    }

    // 构建访问URL
    const avatarUrl = `/uploads/avatars/${req.file.filename}`;
    console.log('生成的URL:', avatarUrl);
    console.log('文件路径:', req.file.path);

    res.json({
      success: true,
      data: {
        url: avatarUrl,
        path: req.file.path
      }
    });
  } catch (error) {
    console.error('上传头像错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '上传头像失败'
    });
  }
});

// 获取单个教师信息
router.get('/teachers/:id', async (req, res) => {
  try {
    const teacher = await Teacher.findById(req.params.id);
    if (!teacher) {
      return res.status(404).json({
        success: false,
        message: '教师不存在'
      });
    }
    res.json({
      success: true,
      data: teacher
    });
  } catch (error) {
    console.error('获取教师信息错误:', error);
    res.status(500).json({
      success: false,
      message: '获取教师信息失败'
    });
  }
});

// 更新教师信息
router.put('/teachers/:id', upload.single('avatar'), async (req, res) => {
  try {
    const { id } = req.params;
    const { name, briefIntro, detailedIntro, phone } = req.body;
    
    // 查找教师
    const teacher = await Teacher.findById(id);
    if (!teacher) {
      return res.status(404).json({
        success: false,
        message: '教师不存在'
      });
    }

    // 处理头像
    let avatarUrl = teacher.avatar;
    if (req.file) {
      avatarUrl = `/uploads/avatars/${req.file.filename}`;
      // 可选：删除旧头像文件
    }

    // 更新教师信息
    const updatedTeacher = await Teacher.findByIdAndUpdate(
      id,
      {
        name,
        avatar: avatarUrl,
        briefIntro,
        detailedIntro,
        phone
      },
      { new: true } // 返回更新后的文档
    );

    res.json({
      success: true,
      data: updatedTeacher
    });
  } catch (error) {
    console.error('更新教师错误:', error);
    res.status(500).json({
      success: false,
      message: error.code === 11000 ? '教师已存在' : '更新教师失败'
    });
  }
});

// 删除教师
router.delete('/teachers/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查找并删除教师
    const deletedTeacher = await Teacher.findByIdAndDelete(id);
    
    if (!deletedTeacher) {
      return res.status(404).json({
        success: false,
        message: '教师不存在'
      });
    }

    // 可选：删除关联的头像文件
    if (deletedTeacher.avatar && !deletedTeacher.avatar.startsWith('http')) {
      const avatarPath = path.join(__dirname, '../public', deletedTeacher.avatar);
      fs.unlink(avatarPath, (err) => {
        if (err) console.error('删除头像文件失败:', err);
      });
    }

    res.json({
      success: true,
      message: '教师删除成功',
      data: deletedTeacher
    });
  } catch (error) {
    console.error('删除教师错误:', error);
    res.status(500).json({
      success: false,
      message: '删除教师失败'
    });
  }
});

// 更新学生信息
router.put('/students/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, gender, phone, class: className, averageScore, isActive } = req.body;

    // 验证输入
    if (!name || !gender || !phone || !className || averageScore === undefined) {
      return res.status(400).json({
        success: false,
        message: '缺少必填字段'
      });
    }

    // 更新学生信息
    const updatedStudent = await Student.findByIdAndUpdate(
      id,
      {
        name,
        gender,
        phone,
        class: className,
        averageScore: parseFloat(averageScore),
        isActive
      },
      { new: true } // 返回更新后的文档
    );

    if (!updatedStudent) {
      return res.status(404).json({
        success: false,
        message: '学生不存在'
      });
    }

    res.json({
      success: true,
      data: updatedStudent
    });
  } catch (error) {
    console.error('更新学生错误:', error);
    res.status(500).json({
      success: false,
      message: error.code === 11000 ? '学生已存在' : '更新学生失败'
    });
  }
});

// 删除学生
router.delete('/students/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const deletedStudent = await Student.findByIdAndDelete(id);
    
    if (!deletedStudent) {
      return res.status(404).json({
        success: false,
        message: '学生不存在'
      });
    }

    res.json({
      success: true,
      message: '学生删除成功',
      data: deletedStudent
    });
  } catch (error) {
    console.error('删除学生错误:', error);
    res.status(500).json({
      success: false,
      message: '删除学生失败'
    });
  }
});

// 课程相关API路由

// 获取课程列表
router.get('/courses', async (req, res) => {
  try {
    const { page = 1, limit = 10, search = '', status = '' } = req.query;
    const skip = (parseInt(page) - 1) * parseInt(limit);
    
    // 构建查询条件
    let query = {};
    if (search) {
      query.$or = [
        { name: { $regex: search, $options: 'i' } },
        { description: { $regex: search, $options: 'i' } },
        { teacherName: { $regex: search, $options: 'i' } }
      ];
    }
    
    // 获取总数
    const total = await Course.countDocuments(query);
    
    // 获取课程列表
    const courses = await Course.find(query)
      .populate('teacher', 'name avatar')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(parseInt(limit));
    
    // 处理旧数据：如果coverImageUrls为空，尝试使用coverImageUrl字段
    const processedCourses = courses.map(course => {
      const courseObj = course.toObject();
      
      // 如果coverImageUrls为空或不存在，但有coverImageUrl字段
      if ((!courseObj.coverImageUrls || courseObj.coverImageUrls.length === 0) && courseObj.coverImageUrl) {
        courseObj.coverImageUrls = [courseObj.coverImageUrl];
        console.log(`课程 "${courseObj.name}" 使用旧字段 coverImageUrl: ${courseObj.coverImageUrl}`);
      }
      
      // 确保fileResources字段被包含在响应中
      if (!courseObj.fileResources) {
        courseObj.fileResources = [];
      }
      
      // 为了兼容前台代码，也添加fileUrls字段
      courseObj.fileUrls = courseObj.fileResources || [];
      
      return courseObj;
    });
    
    res.json({
      success: true,
      data: processedCourses,
      pagination: {
        current: parseInt(page),
        pageSize: parseInt(limit),
        total: total
      }
    });
  } catch (error) {
    console.error('获取课程列表错误:', error);
    console.error('错误堆栈:', error.stack);
    res.status(500).json({
      success: false,
      message: '获取课程列表失败',
      error: error.message
    });
  }
});

// 获取单个课程详情
router.get('/courses/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const course = await Course.findById(id)
      .populate('teacher', 'name avatar')
      .populate('videoResources', 'name videoUrl duration description');
    
    if (!course) {
      return res.status(404).json({
        success: false,
        message: '课程不存在'
      });
    }
    
    // 处理旧数据：如果coverImageUrls为空，尝试使用coverImageUrl字段
    const courseObj = course.toObject();
    if ((!courseObj.coverImageUrls || courseObj.coverImageUrls.length === 0) && courseObj.coverImageUrl) {
      courseObj.coverImageUrls = [courseObj.coverImageUrl];
      console.log(`课程详情 "${courseObj.name}" 使用旧字段 coverImageUrl: ${courseObj.coverImageUrl}`);
    }
    
    // 确保fileResources字段被包含在响应中
    if (!courseObj.fileResources) {
      courseObj.fileResources = [];
    }
    
    // 为了兼容前台代码，也添加fileUrls字段
    courseObj.fileUrls = courseObj.fileResources || [];
    
    res.json({
      success: true,
      data: courseObj
    });
  } catch (error) {
    console.error('获取课程详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取课程详情失败'
    });
  }
});

// 上传课程视频
router.post('/upload-course-video', verifyToken, courseUpload.single('video'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '请选择要上传的视频文件'
      });
    }
    
    const videoUrl = `/uploads/videos/${req.file.filename}`;
    
    console.log('课程视频上传成功:', {
      originalName: req.file.originalname,
      filename: req.file.filename,
      size: req.file.size,
      url: videoUrl
    });
    
    res.json({
      success: true,
      message: '视频上传成功',
      data: {
        url: videoUrl,
        filename: req.file.filename,
        originalName: req.file.originalname,
        size: req.file.size
      }
    });
  } catch (error) {
    console.error('课程视频上传错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '视频上传失败'
    });
  }
});

// 上传课程文档
router.post('/upload-course-file', verifyToken, courseUpload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '请选择要上传的文档文件'
      });
    }
    
    const fileUrl = `/uploads/course-files/${req.file.filename}`;
    
    console.log('课程文档上传成功:', {
      originalName: req.file.originalname,
      filename: req.file.filename,
      size: req.file.size,
      mimetype: req.file.mimetype,
      url: fileUrl
    });
    
    res.json({
      success: true,
      message: '文档上传成功',
      data: {
        url: fileUrl,
        filename: req.file.filename,
        originalName: req.file.originalname,
        size: req.file.size,
        mimetype: req.file.mimetype
      }
    });
  } catch (error) {
    console.error('课程文档上传失败:', error);
    res.status(500).json({
      success: false,
      message: '文档上传失败'
    });
  }
});

// 上传课程图片
router.post('/upload-course-images', verifyToken, courseUpload.array('images', 10), async (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请选择要上传的图片文件'
      });
    }
    
    const imageUrls = req.files.map(file => `/uploads/course-images/${file.filename}`);
    
    console.log('课程图片上传成功:', {
      count: req.files.length,
      urls: imageUrls
    });
    
    res.json({
      success: true,
      message: '图片上传成功',
      data: {
        urls: imageUrls,
        count: req.files.length
      }
    });
  } catch (error) {
    console.error('课程图片上传错误:', error);
    res.status(500).json({
      success: false,
      message: error.message || '图片上传失败'
    });
  }
});

// 添加课程
router.post('/add-course', checkPermission(['add']), async (req, res) => {
  try {
    const {
      name,
      description,
      price,
      coverImageUrls = [],
      videoUrls = [],
      fileUrls = [],
      imageUrls = [],
      teacherId,
      teacherName,
      uploaderUsername
    } = req.body;

    // 验证必填字段
    if (!name || !coverImageUrls || coverImageUrls.length === 0 || !teacherId || !teacherName) {
      return res.status(400).json({
        success: false,
        message: '缺少必填字段'
      });
    }

    // 查找上传用户
    const uploader = await User.findOne({ username: uploaderUsername });
    if (!uploader) {
      return res.status(400).json({
        success: false,
        message: `找不到用户: ${uploaderUsername}`
      });
    }

    // 创建视频资源
    const videoResources = [];
    for (const videoUrl of videoUrls) {
      // 确保视频URL以正确的路径开头
      const validVideoUrl = videoUrl.startsWith('/uploads/videos/') 
        ? videoUrl 
        : `/uploads/videos/${path.basename(videoUrl)}`;

      console.log('准备创建VideoResource:', {
        name: `课程视频_${Date.now()}`,
        videoUrl: validVideoUrl,
        uploader: uploader._id,
        uploaderUsername: uploaderUsername
      });

      const videoResource = new VideoResource({
        name: `课程视频_${Date.now()}`,
        videoUrl: validVideoUrl,
        status: 'published',
        uploader: uploader._id, // 添加必需的uploader字段
        uploaderUsername: uploaderUsername,
        description: '课程视频资源'
      });
      
      const savedVideo = await videoResource.save();
      console.log('VideoResource保存成功，ID:', savedVideo._id);
      videoResources.push(savedVideo._id);
    }

    // 查找教师
    const teacher = await Teacher.findById(teacherId);
    if (!teacher) {
      return res.status(400).json({
        success: false,
        message: `找不到教师: ${teacherId}`
      });
    }

    // 创建课程
    const course = new Course({
      name,
      description,
      price: parseInt(price) || 0,
      coverImageUrls,
      videoResources,
      imageResources: imageUrls,
      fileResources: fileUrls,
      teacher: teacher._id, // 使用教师的ObjectId
      teacherName,
      uploader: uploader._id, // 添加uploader字段
      uploaderUsername
    });

    console.log('准备保存课程数据:', {
      name: course.name,
      videoResources: course.videoResources,
      teacher: course.teacher,
      uploader: course.uploader
    });

    const savedCourse = await course.save();
    console.log('课程保存成功，ID:', savedCourse._id);
    
    // 验证课程是否真的保存到数据库
    const verifyCourse = await Course.findById(savedCourse._id);
    if (!verifyCourse) {
      console.error('❌ 课程保存后无法从数据库中找到！');
      return res.status(500).json({
        success: false,
        message: '课程保存失败'
      });
    }
    
    console.log('✅ 课程验证成功，ID:', verifyCourse._id);
    
    res.json({
      success: true,
      message: '课程添加成功',
      data: savedCourse
    });
  } catch (error) {
    console.error('添加课程错误:', error);
    let errorMessage = '添加课程失败';
    
    if (error.name === 'ValidationError') {
      errorMessage = Object.values(error.errors).map(err => err.message).join(', ');
    } else if (error.code === 11000) {
      errorMessage = '课程已存在';
    }
    
    res.status(500).json({
      success: false,
      message: errorMessage
    });
  }
});

// 删除课程
router.delete('/courses/:id', checkPermission(['delete']), async (req, res) => {
  try {
    const { id } = req.params;
    
    const deletedCourse = await Course.findByIdAndDelete(id);
    
    if (!deletedCourse) {
      return res.status(404).json({
        success: false,
        message: '课程不存在'
      });
    }
    
    // 删除关联的视频资源
    if (deletedCourse.videoResources && deletedCourse.videoResources.length > 0) {
      await VideoResource.deleteMany({ _id: { $in: deletedCourse.videoResources } });
    }
    
    res.json({
      success: true,
      message: '课程删除成功',
      data: deletedCourse
    });
  } catch (error) {
    console.error('删除课程错误:', error);
    res.status(500).json({
      success: false,
      message: '删除课程失败'
    });
  }
});

// 订单相关API

// 获取订单列表
router.get('/orders', async (req, res) => {
  try {
    const { 
      orderStatus, 
      searchText,
      startDate,
      endDate,
      page = 1, 
      pageSize = 10 
    } = req.query;

    // 构建查询条件
    const query = {};
    
    if (orderStatus) {
      query.orderStatus = orderStatus;
    }
    
    if (searchText) {
      query.$or = [
        { orderId: { $regex: searchText, $options: 'i' } },
        { userNickname: { $regex: searchText, $options: 'i' } },
        { phone: { $regex: searchText, $options: 'i' } }
      ];
    }
    
    if (startDate && endDate) {
      query.submitTime = {
        $gte: new Date(startDate),
        $lte: new Date(endDate + 'T23:59:59.999Z')
      };
    }

    // 分页查询
    const [orders, total] = await Promise.all([
      Order.find(query)
        .skip((page - 1) * pageSize)
        .limit(parseInt(pageSize))
        .sort({ submitTime: -1 }),
      Order.countDocuments(query)
    ]);

    res.json({
      success: true,
      data: orders,
      pagination: {
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        total
      }
    });
  } catch (error) {
    console.error('获取订单列表错误:', error);
    res.status(500).json({ 
      success: false,
      message: '获取订单列表失败'
    });
  }
});

// 获取订单详情
router.get('/orders/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const order = await Order.findById(id);
    
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    res.json({
      success: true,
      data: order
    });
  } catch (error) {
    console.error('获取订单详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取订单详情失败'
    });
  }
});

// 更新订单状态
router.put('/orders/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { orderStatus, remark } = req.body;
    
    const updateData = {};
    if (orderStatus) {
      updateData.orderStatus = orderStatus;
      
      // 根据状态更新时间字段
      switch (orderStatus) {
        case 'paid':
          updateData.payTime = new Date();
          break;
        case 'closed':
          updateData.closeTime = new Date();
          break;
        case 'refunded':
          updateData.refundTime = new Date();
          break;
      }
    }
    
    if (remark !== undefined) {
      updateData.remark = remark;
    }
    
    const order = await Order.findByIdAndUpdate(
      id, 
      updateData,
      { new: true, runValidators: true }
    );
    
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    res.json({
      success: true,
      message: '订单状态更新成功',
      data: order
    });
  } catch (error) {
    console.error('更新订单状态错误:', error);
    res.status(500).json({
      success: false,
      message: '更新订单状态失败'
    });
  }
});

// 删除订单
router.delete('/orders/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const deletedOrder = await Order.findByIdAndDelete(id);
    
    if (!deletedOrder) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    res.json({
      success: true,
      message: '订单删除成功',
      data: deletedOrder
    });
  } catch (error) {
    console.error('删除订单错误:', error);
    res.status(500).json({
      success: false,
      message: '删除订单失败'
    });
  }
});

// 创建订单（用于测试）
router.post('/orders', verifyToken, async (req, res) => {
  try {
    const { orderId, userNickname, phone, courseName, orderAmount } = req.body;
    
    const order = new Order({
      orderId,
      userNickname,
      phone,
      courseName,
      orderAmount: parseFloat(orderAmount),
      orderStatus: 'pending'
    });
    
    const savedOrder = await order.save();
    
    res.json({
      success: true,
      message: '订单创建成功',
      data: savedOrder
    });
  } catch (error) {
    console.error('创建订单错误:', error);
    let errorMessage = '创建订单失败';
    
    if (error.name === 'ValidationError') {
      errorMessage = Object.values(error.errors).map(err => err.message).join(', ');
    } else if (error.code === 11000) {
      errorMessage = '订单编号已存在';
    }
    
    res.status(500).json({
      success: false,
      message: errorMessage
    });
  }
});

// 获取仪表板统计数据
router.get('/dashboard/stats', async (req, res) => {
  try {
    // 获取各种统计数据
    const [
      totalStudents,
      totalTeachers,
      totalCourses,
      totalOrders,
      paidOrders,
      pendingOrders,
      closedOrders,
      refundedOrders
    ] = await Promise.all([
      Student.countDocuments(),
      Teacher.countDocuments(),
      Course.countDocuments(),
      Order.countDocuments(),
      Order.countDocuments({ orderStatus: 'paid' }),
      Order.countDocuments({ orderStatus: 'pending' }),
      Order.countDocuments({ orderStatus: 'closed' }),
      Order.countDocuments({ orderStatus: 'refunded' })
    ]);

    // 计算月度收入（已支付订单的总金额）
    const paidOrdersData = await Order.find({ orderStatus: 'paid' });
    const monthlyRevenue = paidOrdersData.reduce((sum, order) => sum + order.orderAmount, 0);

    // 计算订单增长率（简单模拟）
    const orderGrowth = 12.5; // 这里可以根据实际数据计算

    res.json({
      success: true,
      data: {
        totalStudents,
        totalTeachers,
        totalCourses,
        totalOrders,
        monthlyRevenue,
        orderGrowth,
        orderStatusDistribution: {
          paid: paidOrders,
          pending: pendingOrders,
          closed: closedOrders,
          refunded: refundedOrders
        }
      }
    });
  } catch (error) {
    console.error('获取统计数据错误:', error);
    res.status(500).json({
      success: false,
      message: '获取统计数据失败'
    });
  }
});

// 获取订单趋势数据
router.get('/dashboard/order-trend', async (req, res) => {
  try {
    // 模拟12个月的订单数据
    const orderTrend = [
      { month: '1月', count: 120 },
      { month: '2月', count: 132 },
      { month: '3月', count: 101 },
      { month: '4月', count: 134 },
      { month: '5月', count: 90 },
      { month: '6月', count: 230 },
      { month: '7月', count: 210 },
      { month: '8月', count: 182 },
      { month: '9月', count: 191 },
      { month: '10月', count: 234 },
      { month: '11月', count: 290 },
      { month: '12月', count: 330 }
    ];

    res.json({
      success: true,
      data: orderTrend
    });
  } catch (error) {
    console.error('获取订单趋势错误:', error);
    res.status(500).json({
      success: false,
      message: '获取订单趋势失败'
    });
  }
});

// 获取收入统计数据
router.get('/dashboard/revenue', async (req, res) => {
  try {
    // 模拟12个月的收入数据
    const revenueData = [
      { month: '1月', revenue: 15000 },
      { month: '2月', revenue: 18000 },
      { month: '3月', revenue: 22000 },
      { month: '4月', revenue: 25000 },
      { month: '5月', revenue: 28000 },
      { month: '6月', revenue: 32000 },
      { month: '7月', revenue: 35000 },
      { month: '8月', revenue: 38000 },
      { month: '9月', revenue: 42000 },
      { month: '10月', revenue: 45000 },
      { month: '11月', revenue: 48000 },
      { month: '12月', revenue: 52000 }
    ];

    res.json({
      success: true,
      data: revenueData
    });
  } catch (error) {
    console.error('获取收入统计错误:', error);
    res.status(500).json({
      success: false,
      message: '获取收入统计失败'
    });
  }
});

// 分片上传相关API
// 存储分片上传的临时信息
const chunkUploads = new Map();

// 初始化分片上传
router.post('/upload/init', verifyToken, async (req, res) => {
  try {
    const { fileName, fileSize, fileType, chunks } = req.body;
    
    // 生成唯一的文件ID
    const fileId = crypto.createHash('md5').update(`${fileName}-${fileSize}-${Date.now()}`).digest('hex');
    
    // 创建临时目录
    const tempDir = path.join(__dirname, '../public/uploads/temp', fileId);
    if (!fs.existsSync(tempDir)) {
      fs.mkdirSync(tempDir, { recursive: true });
    }
    
    // 存储上传信息
    chunkUploads.set(fileId, {
      fileName,
      fileSize,
      fileType,
      chunks,
      uploadedChunks: new Set(),
      tempDir
    });
    
    res.json({
      success: true,
      data: { fileId }
    });
  } catch (error) {
    console.error('初始化分片上传错误:', error);
    res.status(500).json({
      success: false,
      message: '初始化上传失败'
    });
  }
});

// 上传分片
router.post('/upload/chunk', verifyToken, upload.single('chunk'), async (req, res) => {
  try {
    const { fileId, chunkIndex, fileName } = req.body;
    const chunk = req.file;
    
    if (!chunk) {
      return res.status(400).json({
        success: false,
        message: '未接收到分片数据'
      });
    }
    
    const uploadInfo = chunkUploads.get(fileId);
    if (!uploadInfo) {
      return res.status(400).json({
        success: false,
        message: '上传会话不存在'
      });
    }
    
    // 保存分片到临时目录
    const chunkPath = path.join(uploadInfo.tempDir, `chunk-${chunkIndex}`);
    fs.renameSync(chunk.path, chunkPath);
    
    // 记录已上传的分片
    uploadInfo.uploadedChunks.add(parseInt(chunkIndex));
    
    res.json({
      success: true,
      data: { 
        chunkIndex: parseInt(chunkIndex),
        uploadedChunks: Array.from(uploadInfo.uploadedChunks)
      }
    });
  } catch (error) {
    console.error('上传分片错误:', error);
    res.status(500).json({
      success: false,
      message: '分片上传失败'
    });
  }
});

// 完成分片上传
router.post('/upload/complete', verifyToken, async (req, res) => {
  try {
    const { fileId, fileName } = req.body;
    
    const uploadInfo = chunkUploads.get(fileId);
    if (!uploadInfo) {
      return res.status(400).json({
        success: false,
        message: '上传会话不存在'
      });
    }
    
    // 检查是否所有分片都已上传
    if (uploadInfo.uploadedChunks.size !== uploadInfo.chunks) {
      return res.status(400).json({
        success: false,
        message: '分片上传不完整'
      });
    }
    
    // 合并分片
    const finalFileName = `chunk-${Date.now()}-${Math.floor(Math.random() * 10000)}${path.extname(fileName)}`;
    const finalPath = path.join(__dirname, '../public/uploads/videos', finalFileName);
    
    // 确保目标目录存在
    const targetDir = path.dirname(finalPath);
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true });
    }
    
    // 按顺序合并分片
    const writeStream = fs.createWriteStream(finalPath);
    for (let i = 0; i < uploadInfo.chunks; i++) {
      const chunkPath = path.join(uploadInfo.tempDir, `chunk-${i}`);
      const chunkData = fs.readFileSync(chunkPath);
      writeStream.write(chunkData);
    }
    writeStream.end();
    
    // 清理临时文件
    fs.rmSync(uploadInfo.tempDir, { recursive: true, force: true });
    chunkUploads.delete(fileId);
    
    res.json({
      success: true,
      data: {
        url: `/uploads/videos/${finalFileName}`,
        filename: finalFileName,
        size: uploadInfo.fileSize
      }
    });
  } catch (error) {
    console.error('完成分片上传错误:', error);
    res.status(500).json({
      success: false,
      message: '完成上传失败'
    });
  }
});

// 检查分片上传状态
router.get('/upload/status/:fileId', async (req, res) => {
  try {
    const { fileId } = req.params;
    const uploadInfo = chunkUploads.get(fileId);
    
    if (!uploadInfo) {
      return res.status(404).json({
        success: false,
        message: '上传会话不存在'
      });
    }
    
    res.json({
      success: true,
      data: {
        uploadedChunks: Array.from(uploadInfo.uploadedChunks),
        totalChunks: uploadInfo.chunks,
        fileName: uploadInfo.fileName
      }
    });
  } catch (error) {
    console.error('检查上传状态错误:', error);
    res.status(500).json({
      success: false,
      message: '检查上传状态失败'
    });
  }
});

// 课程排班相关API

// 获取课程排班列表
router.get('/schedules', async (req, res) => {
  try {
    const { page = 1, limit = 10, teacherId, courseId, status, date } = req.query;
    const skip = (parseInt(page) - 1) * parseInt(limit);
    
    // 构建查询条件
    let query = {};
    if (teacherId) query.teacherId = teacherId;
    if (courseId) query.courseId = courseId;
    if (status) query.status = status;
    if (date) {
      const startDate = new Date(date);
      const endDate = new Date(date);
      endDate.setDate(endDate.getDate() + 1);
      query.date = { $gte: startDate, $lt: endDate };
    }
    
    // 获取总数
    const total = await Schedule.countDocuments(query);
    
    // 获取排班列表
    const schedules = await Schedule.find(query)
      .populate('courseId', 'name')
      .populate('teacherId', 'name')
      .sort({ date: 1, startTime: 1 })
      .skip(skip)
      .limit(parseInt(limit));
    
    res.json({
      success: true,
      data: schedules,
      pagination: {
        current: parseInt(page),
        pageSize: parseInt(limit),
        total: total
      }
    });
  } catch (error) {
    console.error('获取课程排班列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取课程排班列表失败'
    });
  }
});

// 获取单个课程排班详情
router.get('/schedules/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const schedule = await Schedule.findById(id)
      .populate('courseId', 'name')
      .populate('teacherId', 'name');
    
    if (!schedule) {
      return res.status(404).json({
        success: false,
        message: '课程排班不存在'
      });
    }
    
    res.json({
      success: true,
      data: schedule
    });
  } catch (error) {
    console.error('获取课程排班详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取课程排班详情失败'
    });
  }
});

// 添加课程排班
router.post('/schedules', verifyToken, async (req, res) => {
  try {
    console.log('收到排班数据:', req.body);
    
    const {
      courseId,
      teacherId,
      courseName,
      teacherName,
      date,
      startTime,
      endTime,
      classroom,
      status = 'scheduled',
      description,
      createdByUsername
    } = req.body;

    // 验证必填字段
    if (!courseId || !teacherId || !courseName || !teacherName || !date || !startTime || !endTime || !classroom) {
      return res.status(400).json({
        success: false,
        message: '缺少必填字段'
      });
    }

    // 查找创建用户
    const createdBy = await User.findOne({ username: createdByUsername });
    if (!createdBy) {
      return res.status(400).json({
        success: false,
        message: `找不到用户: ${createdByUsername}`
      });
    }

    // 检查时间冲突 - 暂时注释掉，避免复杂的查询逻辑导致错误
    /*
    const conflictSchedule = await Schedule.findOne({
      teacherId,
      date: new Date(date),
      $and: [
        { startTime: { $lt: endTime } },
        { endTime: { $gt: startTime } }
      ]
    });

    if (conflictSchedule) {
      return res.status(400).json({
        success: false,
        message: '该时间段已有排班，请选择其他时间'
      });
    }
    */

    // 创建排班
    const schedule = new Schedule({
      courseId,
      teacherId,
      courseName,
      teacherName,
      date: new Date(date),
      startTime,
      endTime,
      classroom,
      status,
      description,
      createdBy: createdBy._id,
      createdByUsername
    });

    const savedSchedule = await schedule.save();
    
    res.json({
      success: true,
      message: '课程排班添加成功',
      data: savedSchedule
    });
  } catch (error) {
    console.error('添加课程排班错误:', error);
    let errorMessage = '添加课程排班失败';
    
    if (error.name === 'ValidationError') {
      errorMessage = Object.values(error.errors).map(err => err.message).join(', ');
    }
    
    res.status(500).json({
      success: false,
      message: errorMessage
    });
  }
});

// 更新课程排班
router.put('/schedules/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;

    // 检查排班是否存在
    const existingSchedule = await Schedule.findById(id);
    if (!existingSchedule) {
      return res.status(404).json({
        success: false,
        message: '课程排班不存在'
      });
    }

    // 如果更新了时间，检查冲突
    if (updateData.date || updateData.startTime || updateData.endTime) {
      const conflictSchedule = await Schedule.findOne({
        _id: { $ne: id },
        teacherId: updateData.teacherId || existingSchedule.teacherId,
        date: new Date(updateData.date || existingSchedule.date),
        $or: [
          {
            startTime: { $lt: updateData.endTime || existingSchedule.endTime },
            endTime: { $gt: updateData.startTime || existingSchedule.startTime }
          }
        ]
      });

      if (conflictSchedule) {
        return res.status(400).json({
          success: false,
          message: '该时间段已有排班，请选择其他时间'
        });
      }
    }

    // 更新排班
    const updatedSchedule = await Schedule.findByIdAndUpdate(
      id,
      updateData,
      { new: true, runValidators: true }
    );

    res.json({
      success: true,
      message: '课程排班更新成功',
      data: updatedSchedule
    });
  } catch (error) {
    console.error('更新课程排班错误:', error);
    let errorMessage = '更新课程排班失败';
    
    if (error.name === 'ValidationError') {
      errorMessage = Object.values(error.errors).map(err => err.message).join(', ');
    }
    
    res.status(500).json({
      success: false,
      message: errorMessage
    });
  }
});

// 删除课程排班
router.delete('/schedules/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const schedule = await Schedule.findById(id);
    if (!schedule) {
      return res.status(404).json({
        success: false,
        message: '课程排班不存在'
      });
    }

    await Schedule.findByIdAndDelete(id);
    
    res.json({
      success: true,
      message: '课程排班删除成功'
    });
  } catch (error) {
    console.error('删除课程排班错误:', error);
    res.status(500).json({
      success: false,
      message: '删除课程排班失败'
    });
  }
});

// 引入支付宝服务
let AlipaySdk = require("alipay-sdk")
let AlipaySdkFormData = require("alipay-sdk/lib/form")

// 创建图书购买订单
router.post('/create-book-order', verifyToken, async (req, res) => {
  try {
    const { bookId, bookTitle, price, userNickname, phone } = req.body;
    
    // 生成订单号
    const orderId = Math.floor(1000000 + Math.random() * 9000000).toString();
    
    // 创建订单记录
    const order = new Order({
      orderId,
      userNickname,
      phone,
      productType: 'book',
      productName: bookTitle,
      productId: bookId,
      orderAmount: parseFloat(price.replace('¥', '')),
      orderStatus: 'pending'
    });

    const savedOrder = await order.save();

    res.json({
      success: true,
      message: '订单创建成功',
      data: {
        orderId: savedOrder.orderId,
        bookTitle: savedOrder.productName,
        amount: savedOrder.orderAmount
      }
    });
  } catch (error) {
    console.error('创建图书订单失败:', error);
    res.status(500).json({
      success: false,
      message: '创建订单失败'
    });
  }
});

// 支付宝支付接口
router.post('/alipay', async function (req, res) {
  try {
    const { outTradeNo, subject, totalAmount } = req.body;

    const alipaySdk = new AlipaySdk({
      // 设置应用 ID
      appId: '9021000150603290',
      // 设置应用私钥
      privateKey: "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCqMyujNEG34BEFfrFcMMEr9VAXLnQzxBmQeBL1CQkz1x1Vz3UJDBWq3yh4mfMBz3/9xEfOcajSAVtyIG9rwfkyVcTAtEN2I6raCiAww/XWWFBQANh8iM3F3ymcflcHpsbvJBrgKiQPpnC1xbDkMO2Q6XYNRxLtT1tI2kSzLg5z9X1LggAoT0WKoLRU/eg8dI7s4PXV9gMue4KiZoNKMIkbMXiL0HUPiO5vO6rVrjqL85Q58mB481Iv9cOIy/T55u0FAjBleIvkLBb6QtGCQONUOPNXRScP/XdcEFlUAzWBmSjilNW/nxrMoX+nWcYgnhS4XlQyQXEgqyw9T+xCz8RnAgMBAAECggEAfFY3idnSLMcXCEGexi+j3z4uDVFVeL/IwT7G8pVwUJvVBWwyHrLiXVr7kOc+nNL+uN+caZek8g4lxQEnBLzHFNuNig3mvradyP3euGFgBf+sZFXJ0WiLkwNNvdKaN6/B4tAohhyjDX/VFSXf7URFOTkkkdybWhxAHr+9snxx+IloagtGU9m3R0cE1fK6Ff68efXEhaYMH2viMraRUeVdt5xxrKVzNnqMYaLtED+hr3DpG8eHiNX5h60mOvYBjNZUB0xFOJ+B/vrCEqDJSeftFXOXMQneBi7T8nDTSpw1mbaoBw2OHeKhw0B66J7MN+6aWNJWXf3AHvBqHOikTBRX6QKBgQD3Qeypn7toPdI82DmI5UNWWonK/IvJkH7KGdb2Xbr+ddjDyZlHQGaBq2TzTFCpBdun0S6M6w4Sx+frQ3lZHMpXiuinHpsRpB91aOmT5tnvaSKzpN7J12myYQdoc2ElqSbnOaVLuAUHvK/HbcciWMlcHTvtp8T1KYmkUVADBjdhFQKBgQCwN8BWPn0k6xJiWcik/3bj7KJzeHGDqQ42iHtWqNOAcv96hK0EhQq44mf1xm+E0EJNFzQFg9h/lrrlkXqv/wMzxcez0uDzJj7w68oCk9GkaqRldEsyDdrutRouYy7/d8q8OegglXRmsMbBXidIaXIvOOv2HMkud5MYqhUs1d1WiwKBgQDnUzQZVim9UulYp2rcmrGvHrF/yVr2z0rvxdEJWZPS8WpFcl0G/kdo1XNy9FkaaTKiBOCqUlcuVvyxbMUhDAB6eqlDgSzPCl+sNuUgzH/krtYagAs3h2OJ0aFepWOkGmcdOR9egeGi5XMG/7uodKyek3M32xg3zg7KPpC+45f4KQKBgAKTbg5Ur4OgpA4n/dTbnyNJzD4f3pjsGbcWW6cypJTWGYHy+ox8XWHCfX6MPgkU+kMiObJy8PE8hNLiQ4bbFXLmSzsHtB4ZywW+jJ9pBcF/hZOuFYNPzIl8wDs5W/CEEcSanBgN1zvBDca5150pXW/vRxO76/zv5oiPw+t53NhtAoGBALNad4FEvQByCtVMGK+rF3WiDVa+hMp8fn/Rw0wjrqm3Y8eLwiNsv+IZPzRPkPS83w2zVt8qbPbSVbW1OFWzvnChBqvMRH6T0nhuV/Y5P19zPBdocozpKjbf6aU8FoRah66Z5VuKWjLBjissBB38rzfay7jJTa8lm90yBHl2P9jj",
      // 设置支付宝公钥
      alipayPublicKey: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhBe1DJp1oMojyRLBv53i461lf46SrUFRS/xSroN6y7eXYyXhm/+Wd+9tNvpB67VzYLULkjCWQDy7y8D/SvrG5hm0LgRtX2rrRkvbbHAHKv4ebfi+PvxKlo/4TLkGwtyQGy6PAPoXwt/UTFr6x2oyhlh8x3M1AT3ANbGByCwATkvoTdMtxeGMMeBM/RUfuT/HdZBCgvc9fIyKDE07zgnG7jb0EXF4wSJ7oQQxQ/7qY2uhmbNmOSWohqhsv//wtud62oEZoZz2XaQnk/kZ5Q11lzksaTqVo8JtVFP0ERr3yhiFLWDSdrqFi4JldutI7EL4ztSmsWi98JDAUOrofd7SeQIDAQAB",
      // 密钥类型，请与生成的密钥格式保持一致，参考平台配置一节
      // keyType: 'PKCS1',
      // 设置网关地址，默认是 https://openapi.alipay.com
      // endpoint: 'https://openapi.alipay.com',
      "gateway": "https://openapi-sandbox.dl.alipaydev.com/gateway.do"
    })
    
    const formData = new AlipaySdkFormData();
    formData.addField("bizContent", {
      // 一个订单只能支付一次
      out_trade_no: outTradeNo,
      product_code: "FAST_INSTANT_TRADE_PAY",  // 支付信息的订单编号 前端在确定订单的时候会生产订单信息 包括订单编号
      subject: subject, // 商品名称
      body: "智能图书购买",
      total_amount: totalAmount.toString()  // 支付金额，必须转换为字符串
    })

    // 支付成功后跳转到前端的一个路由
    formData.addField("returnUrl", "http://localhost:5173/payment-success")

    // 支付有PC端和移动端 
    //   alipay.trade.page.pay PC端
    // alipay.trade.wap.pay 移动端
    let result = await alipaySdk.exec("alipay.trade.page.pay", {}, {
      formData: formData
    })
    console.log(result, 123123);
    res.send(result)
    
  } catch (error) {
    console.error('支付宝支付失败:', error);
    res.status(500).json({
      success: false,
      message: '支付创建失败'
    });
  }
});

// 支付宝回调接口
router.post('/alipay/callback', async (req, res) => {
  try {
    console.log('支付宝回调数据:', req.body);
    
    // 支付宝回调可能使用不同的参数名，需要兼容处理
    const outTradeNo = req.body.out_trade_no || req.body.outTradeNo;
    const tradeNo = req.body.trade_no || req.body.tradeNo;
    const tradeStatus = req.body.trade_status || req.body.tradeStatus;
    const totalAmount = req.body.total_amount || req.body.totalAmount;
    
    console.log('解析后的回调参数:', { outTradeNo, tradeNo, tradeStatus, totalAmount });
    
    // 查找并更新订单
    const order = await Order.findOne({ orderId: outTradeNo });
    if (order) {
      console.log('找到订单:', order.orderId, '当前状态:', order.orderStatus);
      
      // 支付宝沙箱环境可能使用不同的状态值
      if (tradeStatus === 'TRADE_SUCCESS' || tradeStatus === 'TRADE_FINISHED' || tradeStatus === 'success') {
        order.orderStatus = '已支付';
        order.alipayTradeNo = tradeNo;
        order.payTime = new Date();
        await order.save();
        console.log(`订单 ${outTradeNo} 支付成功，状态已更新为: 已支付`);
      } else {
        console.log(`订单 ${outTradeNo} 状态为: ${tradeStatus}，不更新订单状态`);
      }
    } else {
      console.log(`未找到订单: ${outTradeNo}`);
    }

    res.send('success');
  } catch (error) {
    console.error('支付宝回调处理失败:', error);
    res.status(500).send('fail');
  }
});

// 获取所有订单列表（后台管理用）
router.get('/orders', verifyToken, async (req, res) => {
  try {
    const { page = 1, limit = 10, status, productType } = req.query;
    const skip = (page - 1) * limit;
    
    // 构建查询条件
    const query = {};
    if (status) query.orderStatus = status;
    if (productType) query.productType = productType;
    
    // 获取订单总数
    const total = await Order.countDocuments(query);
    
    // 获取订单列表
    const orders = await Order.find(query)
      .sort({ submitTime: -1 })
      .skip(skip)
      .limit(parseInt(limit));

    res.json({
      success: true,
      data: orders,
      pagination: {
        current: parseInt(page),
        pageSize: parseInt(limit),
        total
      }
    });
  } catch (error) {
    console.error('获取订单列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单列表失败'
    });
  }
});

// 获取用户订单列表
router.get('/user/orders', verifyToken, async (req, res) => {
  try {
    const { userNickname } = req.query;
    
    const orders = await Order.find({ 
      userNickname,
      productType: 'book'
    }).sort({ submitTime: -1 });

    res.json({
      success: true,
      data: orders
    });
  } catch (error) {
    console.error('获取用户订单失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单失败'
    });
  }
});

// 获取订单详情
router.get('/order/:orderId', verifyToken, async (req, res) => {
  try {
    const { orderId } = req.params;
    
    const order = await Order.findOne({ orderId });
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    res.json({
      success: true,
      data: order
    });
  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单详情失败'
    });
  }
});

// 手动更新订单状态（用于测试）
router.put('/order/:orderId/status', verifyToken, async (req, res) => {
  try {
    const { orderId } = req.params;
    const { status } = req.body;
    
    const order = await Order.findOne({ orderId });
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    order.orderStatus = status;
    if (status === '已支付') {
      order.payTime = new Date();
    }
    await order.save();

    res.json({
      success: true,
      message: '订单状态更新成功',
      data: order
    });
  } catch (error) {
    console.error('更新订单状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新订单状态失败'
    });
  }
});

module.exports = { router, setupWebSocket };